package com.zzq.my.jetpacks.net.Util;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 描述：Retrofit图片、文字、组合上传工具类
 * 作者：LiangAn
 * 时间: 2022/1/6 11:44
 * emil:1449368524@qq.com
 * 备注:
 */
public final class RxPartMapUtils {

    /**
     * 转文字
     *
     * @param value
     * @return
     */
    public static RequestBody toRequestBodyOfText(String value) {
        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
        return body;
    }

    /**
     * 转图片
     *
     * @param pFile
     * @return
     */
    public static RequestBody toRequestBodyOfImage(File pFile) {
//        RequestBody requestBody = RequestBody.create(pFile, MediaType.parse("image/*"));
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), pFile);
        return fileBody;
    }

    /**
     * 转图片或者文件
     *
     * @param pFile
     * @return
     */
    public static RequestBody toRequestBodyOfFile(File pFile) {
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), pFile);
        return fileBody;
    }

    /**
     * 转File 为  MultipartBody.Part
     * @param file
     * @return  MultipartBody.Part
     */
    public static MultipartBody.Part toRequestBodyOfPart(File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        return part;
    }


    /**
     * 多图片和文字上传可以参考下面的例子
     */
    private void addFileTes() {
        Map<String, RequestBody> map = new HashMap<>();
        //text属性如何放入
        map.put("name", RxPartMapUtils.toRequestBodyOfText("mAccount"));

        List<String> fileList = new ArrayList<>();
        //file属性如何放入
        for (String _selectedPhoto : fileList) {
            File _file = new File(_selectedPhoto);
            if (_file.exists()) {
                RequestBody requestBody = RxPartMapUtils.toRequestBodyOfImage(_file);
                map.put("filename=" + _file.getName(), requestBody);
            }
        }
    }

}
